package com.aliwo.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliwo.exception.ControllerException;
import com.aliwo.request.SaveHttpJobInfoRequest;
import com.aliwo.service.HttpApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.powerjob.common.enums.InstanceStatus;
import tech.powerjob.common.response.InstanceInfoDTO;
import tech.powerjob.common.response.JobInfoDTO;
import tech.powerjob.common.response.ResultDTO;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author:xuyayuan
 * @date:2021/7/21 21:35
 * @description:TODO
 */
@SuppressWarnings("all")
@Api(tags = "HttpApi处理器模块")
@RestController
@RequestMapping("/powerjob/api")
public class HttpApiController {

    @Autowired
    private HttpApiService httpApiService;

    @ApiOperation("httpApi新增任务")
    @PostMapping("/save")
    public ResultDTO<Long> saveApiJobInfo(@ApiParam(value = "httpAIP创建任务请求对象") @RequestBody SaveHttpJobInfoRequest request) throws Exception {
        JSONObject params = new JSONObject();
        preValid(request, params);
        request.valid();
        httpApiService.saveApiJob(request);
        return ResultDTO.success(null);
    }


    //@ApiOperation(value = "查找任务")
    //@GetMapping("/{jobId}")
    //public ResultDTO<JobInfoDTO> fetchJob(@ApiParam(value = "任务ID") @PathVariable Long jobId) {
    //    ResultDTO<JobInfoDTO> jobInfoDTO = httpApiService.fetchJob(jobId);
    //    return ResultDTO.success(jobInfoDTO.getData());
    //}
    //
    //@ApiOperation(value = "禁用某个任务")
    //@GetMapping("/disableJob/{jobId}")
    //public ResultDTO<Void> disableJob(@ApiParam(value = "任务ID") @PathVariable Long jobId) {
    //    httpApiService.disableJob(jobId);
    //    return ResultDTO.success(null);
    //}
    //
    //@ApiOperation(value = "启用某个任务")
    //@GetMapping("/enableJob/{jobId}")
    //public ResultDTO<Void> enableJob(@ApiParam(value = "任务ID") @PathVariable Long jobId) {
    //    httpApiService.enableJob(jobId);
    //    return ResultDTO.success(null);
    //}
    //
    //@ApiOperation(value = "删除某个任务")
    //@DeleteMapping("/deleteJob/{jobId}")
    //public ResultDTO<Void> deleteJob(@ApiParam(value = "任务ID") @PathVariable Long jobId) {
    //    httpApiService.deleteJob(jobId);
    //    return ResultDTO.success(null);
    //}
    //
    //@ApiOperation(value = "运行某个任务")
    //@PostMapping("/runJob")
    //public ResultDTO<Long> runJob(@ApiParam(value = "任务ID") @RequestParam(required = true) Long jobId,
    //                              @ApiParam(value = "任务实例参数") @RequestParam(required = false) String instanceParams,
    //                              @ApiParam(value = "延迟执行时间") @RequestParam(required = false) Long delay) {
    //    ResultDTO<Long> longResultDTO = httpApiService.runJob(jobId, instanceParams, delay == null ? 0L : delay);
    //    return ResultDTO.success(longResultDTO.getData());
    //}
    //
    ///* ************* Instance 区 ************* */
    //
    //@ApiOperation(value = "停止某个任务实例")
    //@PostMapping("/stopInstance")
    //public ResultDTO<Void> stopInstance(@ApiParam("任务实例ID") @RequestParam Long instanceId) {
    //    httpApiService.stopInstance(instanceId);
    //    return ResultDTO.success(null);
    //}
    //
    //@ApiOperation(value = "取消某个任务实例")
    //@PostMapping("/cancelInstance")
    //public ResultDTO<Void> cancelInstance(Long instanceId) {
    //    httpApiService.cancelInstance(instanceId);
    //    return ResultDTO.success(null);
    //}
    //@ApiOperation(value = "查询某个任务实例")
    //@PostMapping("/fetchInstanceInfo")
    //public ResultDTO<InstanceInfoDTO> fetchInstanceInfo(Long instanceId) {
    //    return ResultDTO.success(httpApiService.fetchInstanceInfo(instanceId).getData());
    //}
    //
    //@ApiOperation(value = "查询某个任务实例状态")
    //@PostMapping("/fetchInstanceStatus")
    //public ResultDTO<Integer> fetchInstanceStatus(Long instanceId) {
    //    InstanceStatus instanceStatus = InstanceStatus.of(httpApiService.fetchInstanceStatus(instanceId).getData());
    //    return ResultDTO.success(instanceStatus.getV());
    //}


    /**
     * 功能描述: 创建任务参数，校验
     *
     * @param saveHttpJobInfoRequestrequest
     * @param params
     * @return void
     * @author xuyayuan
     */
    private void preValid(SaveHttpJobInfoRequest saveHttpJobInfoRequestrequest, JSONObject params) {
        Optional.ofNullable(saveHttpJobInfoRequestrequest.getUrl())
                .orElseThrow(() -> new ControllerException("APP:SYSTEM:APP_SAVE", "Url不能为空", "ServiceException.system" +
                        ".application.exist"));
        Optional.ofNullable(saveHttpJobInfoRequestrequest.getMethod())
                .orElseThrow(() -> new ControllerException("APP:SYSTEM:APP_SAVE", "已存在的应用KEY", "ServiceException" +
                        ".system" +
                        ".application.exist"));
        params.put("url", saveHttpJobInfoRequestrequest.getUrl());
        params.put("method", saveHttpJobInfoRequestrequest.getMethod());
        Optional.ofNullable(saveHttpJobInfoRequestrequest.getHeaders()).ifPresent(headers -> {
            Map<String, String> map = new HashMap<>();
            map.put(headers, headers);
            params.put("headers", map);
        });
        Optional.ofNullable(saveHttpJobInfoRequestrequest.getMediaType()).ifPresent(mediaType -> {
            params.put("mediaType", mediaType);
        });
        Optional.ofNullable(saveHttpJobInfoRequestrequest.getBody()).ifPresent(body -> {
            params.put("body", body);
        });

        saveHttpJobInfoRequestrequest.setJobParams(params.toJSONString());
        saveHttpJobInfoRequestrequest.setProcessorInfo("tech.powerjob.official.processors.impl.HttpProcessor");
    }

}
